package com.ulic.customerManApplication.memberenjoymodule.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.bo.Organization;
import com.ulic.customerManApplication.commonmodule.service.OrganizationService;
import com.ulic.customerManApplication.commonmodule.vo.ImpDataInfor;
import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.memberenjoymodule.bo.MemberEnjoyActivity;
import com.ulic.customerManApplication.memberenjoymodule.service.MemberEnjoyService;
import com.ulic.customerManApplication.memberenjoymodule.vo.MemberEnjoyVO;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.DownloadDemo;
import com.ulic.customerManApplication.util.excel.DownloadExcel;
import com.ulic.customerManApplication.util.excel.ExpMemberEnjoys;
import com.ulic.customerManApplication.util.excel.UploadFile;
@Component("memberEnjoyAction")
@Scope("prototype")
public class MemberEnjoyAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MemberEnjoyService memberEnjoyService;
	private MemberEnjoyActivity memberEnjoy;
	private String impDataInfor;
	private OrganizationService organizationService;
	private File memberEnjoysFile;
    private String fileName;
    
    private String subCityHidden;
	
	public String getSubCityHidden() {
		return subCityHidden;
	}
	public void setSubCityHidden(String subCityHidden) {
		this.subCityHidden = subCityHidden;
	}
	
	public MemberEnjoyActivity getMemberEnjoy() {
		return memberEnjoy;
	}
	public void setMemberEnjoy(MemberEnjoyActivity memberEnjoy) {
		this.memberEnjoy = memberEnjoy;
	}
	public MemberEnjoyService getMemberEnjoyService() {
		return memberEnjoyService;
	}
	public File getMemberEnjoysFile() {
		return memberEnjoysFile;
	}
	public String getImpDataInfor() {
		return impDataInfor;
	}
	public void setImpDataInfor(String impDataInfor) {
		this.impDataInfor = impDataInfor;
	}
	public void setMemberEnjoysFile(File memberEnjoysFile) {
		this.memberEnjoysFile = memberEnjoysFile;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	@Resource
	public void setMemberEnjoyService(MemberEnjoyService memberEnjoyService) {
		this.memberEnjoyService = memberEnjoyService;
	}
    @Resource
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public OrganizationService getOrganizationService() {
		return organizationService;
	}
	@Override
	public String execute() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		PagerModel pm = memberEnjoyService.findMemberEnjoyActivities(curPage);
		httpServletRequest.setAttribute("pm",pm);
		return SUCCESS;
	}
	
	public String searchMemberEnjoys(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		String buttonName = httpServletRequest.getParameter("buttonType");
		if(!"exp".equals(buttonName)){
		String startDate = httpServletRequest.getParameter("startDate");
		String endDate = httpServletRequest.getParameter("endDate");
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		MemberEnjoyVO memberEnjoyVO = new MemberEnjoyVO();
		memberEnjoyVO.setStartDate(startDate);
		memberEnjoyVO.setEndDate(endDate);
		memberEnjoyVO.setRoleName(roleName);
		memberEnjoyVO.setUser(user);
		if(memberEnjoy==null){
			memberEnjoy = new MemberEnjoyActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 memberEnjoy.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 memberEnjoy.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 memberEnjoy.setSubCity(organ.getUm_organ_id());
			 }
		} 
		memberEnjoyVO.setMemberEnjoy(memberEnjoy);
		PagerModel pm = memberEnjoyService.findMemberEnjoyActivities(memberEnjoyVO, curPage);
		httpServletRequest.setAttribute("pm",pm);
		
		MemberEnjoyActivity mActivity = null;
		if(pm.getTotal()!=0){
			for(Object obj:memberEnjoyService.findMemberEnjoyActivities(memberEnjoyVO,pm.getTotal()).getDatas()){
				if(obj instanceof MemberEnjoyActivity){
					mActivity = (MemberEnjoyActivity)obj;
					if(mActivity.getParticipantsNum()!=null && mActivity.getParticipantsNum()>0){
						memberEnjoyVO.setTotalPNum(mActivity.getParticipantsNum()+memberEnjoyVO.getTotalPNum());
					}
					if(mActivity.getOrganizeFee()!=null){
						try{
							Double.parseDouble(mActivity.getOrganizeFee());
						}catch(Exception e){
							e.printStackTrace();
						}
						memberEnjoyVO.setTotalOrganFee(Double.parseDouble(mActivity.getOrganizeFee())+memberEnjoyVO.getTotalOrganFee());
					}
				}
			}
		}
		httpServletRequest.setAttribute("memberEnjoyVO", memberEnjoyVO);
		httpServletRequest.setAttribute("startDate", startDate);
		httpServletRequest.setAttribute("endDate", endDate);
		httpServletRequest.setAttribute("roleName",roleName);
		return SUCCESS;
		}else{
			return expMemberEnjoys();
		}
	}
	public String toSaveMemberEnjoy()throws Exception{
		String roleName = (String)session.get("rolename");
		if(memberEnjoy==null){
			memberEnjoy = new MemberEnjoyActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 memberEnjoy.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 memberEnjoy.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 memberEnjoy.setSubCity(organ.getUm_organ_id());
			 }
		} 
		return SUCCESS;
	}
	public String saveMemberEnjoy()throws Exception{
		memberEnjoy.setCreateDate(new Date());
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		memberEnjoy.setUser(user);
		if(memberEnjoy.getParticipantsNum()==null){
			memberEnjoy.setParticipantsNum(0);
		 }
		memberEnjoyService.addMemberEnjoyActivity(memberEnjoy);
		return SUCCESS;
	}
	public String viewMemberEnjoy()throws Exception{
		memberEnjoy = memberEnjoyService.findMemberEnjoyActivity(memberEnjoy.getId());
		return SUCCESS;
	}
	public String updateMemberEnjoy()throws Exception{
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		memberEnjoy = memberEnjoyService.findMemberEnjoyActivity(memberEnjoy.getId());
		String roleName = (String)session.get("rolename");
		if(!"THIRDADMIN".equals(roleName)){
			httpServletRequest.setAttribute("expensedCityList", organizationService.findOrganizationByParentId(memberEnjoy.getSubCompany()));
		}
		return SUCCESS;
	}
	public String updatedMemberEnjoy()throws Exception{
		 User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		 memberEnjoy.setUser(user);
		 if(memberEnjoy.getParticipantsNum()==null){
				memberEnjoy.setParticipantsNum(0);
			 }
		 memberEnjoyService.modifyMemberEnjoyActivity(memberEnjoy);
		 return SUCCESS;
	}
	public String deleteMemberEnjoy()throws Exception{
		memberEnjoy = memberEnjoyService.findMemberEnjoyActivity(memberEnjoy.getId());
		memberEnjoyService.removeMemberEnjoyActivity(memberEnjoy);
		return SUCCESS;
	}
	public String impMemberEnjoys() throws Exception{
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		long date = new Date().getTime();
		ImpDataInfor impDataInfor = new ImpDataInfor();
		List<Integer> errorNumbers = new ArrayList<Integer>();
		String rolename = session.get("rolename").toString();
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		if(fileName != null && fileName.length() !=0){
			fileName = UploadFile.upload(memberEnjoysFile, fileName,date);//先将文件上传到服务器
			File f = new File(realPath+"/"+fileName);  
			List<MemberEnjoyActivity> memberEnjoyActivities = new ArrayList<MemberEnjoyActivity>();
			MemberEnjoyActivity  memberEnjoyActivity = null;
			Organization organization = null;
			Organization cityOrgan = null;
			Organization subCompanyOrgan = null;
			Organization subCityOrgan = null;
			try {   
				FileInputStream is = new FileInputStream(f);  //读取服务器上的文件 
				HSSFWorkbook wbs = new HSSFWorkbook(is);   
				HSSFSheet childSheet = wbs.getSheetAt(0); 
				loop:	for (int j = 1; j <= childSheet.getLastRowNum(); j++) {   
						HSSFRow row = childSheet.getRow(j);   
						memberEnjoyActivity = new MemberEnjoyActivity();
						if (null != row) {   
							for (int k = 0; k < 8; k++) {   
								String value = null;
								int number = 0;
								HSSFCell cell = row.getCell((short)k);   
								if (null != cell) {   
									switch (cell.getCellType()) {   
									case HSSFCell.CELL_TYPE_NUMERIC: // 数字   
										System.out.print(cell.getNumericCellValue()   
												+ "   ");
										number = (int)cell.getNumericCellValue();
										value = String.valueOf(cell.getNumericCellValue());
										break;   
									case HSSFCell.CELL_TYPE_STRING: // 字符串   
										System.out.print(cell.getStringCellValue()   
												+ "   "); 
										value = cell.getStringCellValue();
										break;   
									case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
										System.out.println(cell.getBooleanCellValue()   
												+ "   ");   
										break;   
									case HSSFCell.CELL_TYPE_FORMULA: // 公式   
										System.out.print(cell.getCellFormula() + "   ");   
										break;   
									case HSSFCell.CELL_TYPE_BLANK: // 空值   
										System.out.println(" ");   
										break;   
									case HSSFCell.CELL_TYPE_ERROR: // 故障   
										System.out.println(" ");   
										break;   
									default:   
										System.out.print("未知类型   ");   
										break;   
									} 
									
								} else {   
									System.out.print("-   ");   
									value="";
								} 
								switch(k){
								case 0:
									memberEnjoyActivity.setActivityDate(value);
									break;
								case 1:
									memberEnjoyActivity.setEnjoyActivity(value);
									break;
								case 2:
									organization = organizationService.getOrganizationByFullName(value);
									if (organization != null) {
										if(!"ADMIN".equals(rolename)){
											subCompanyOrgan = (Organization)session.get("barchList");
											if(subCompanyOrgan.getUm_organ_id().equals(organization.getUm_organ_id())){
												memberEnjoyActivity.setSubCompany(organization.getUm_organ_id());
												memberEnjoyActivity.setSubComName(value);
											}else{
												errorNumbers.add(j);
												impDataInfor.setFailResaon("4");
												continue loop;
										    }
										}
										if("ADMIN".equals(rolename)){
											memberEnjoyActivity.setSubCompany(organization.getUm_organ_id());
											memberEnjoyActivity.setSubComName(value);
										}
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("1");
										continue loop;
									}
								case 3:
									cityOrgan = organizationService.getOrganizationByFullName(value);
									if(cityOrgan!=null){
										if("THIRDADMIN".equals(rolename)){
											subCityOrgan = (Organization)session.get("expensedList");
											if(subCityOrgan.getUm_organ_id().equals(cityOrgan.getUm_organ_id())){
												memberEnjoyActivity.setSubCity(cityOrgan.getUm_organ_id());
												memberEnjoyActivity.setSubCityName(value);
											}else{
												errorNumbers.add(j);
												impDataInfor.setFailResaon("4");
												continue loop;
											}
										}
										List<Organization> organList = organizationService.findOrganizationByParentId(organization.getUm_organ_id());
										boolean flag  = false;
										if(!"THIRDADMIN".equals(rolename)){
											for(Organization or : organList){
												if(or.getUm_organ_id().equals(cityOrgan.getUm_organ_id())){
													memberEnjoyActivity.setSubCity(cityOrgan.getUm_organ_id());
													memberEnjoyActivity.setSubCityName(value);
													flag = true;
												}
											}
											if(!flag){
												errorNumbers.add(j);
												impDataInfor.setFailResaon("5");
												continue loop;
											}
										}
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("2");
										continue loop;
									}
								case 4:
									memberEnjoyActivity.setOrganizeFee(value);
									break;
								case 5:
									memberEnjoyActivity.setParticipantsNum(number);
									break;
								case 6:
									memberEnjoyActivity.setActivityPlace(value);
									break;
								case 7:
									if(value != null && value.length() > 0){
										memberEnjoyActivity.setOaSph(value);
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("6");
										continue loop;
									}
								default:  
									break;
								}
							}   
						}
						memberEnjoyActivity.setCreateDate(new Date()); 
						memberEnjoyActivity.setUser(user);
						memberEnjoyActivities.add(memberEnjoyActivity);
					}
					memberEnjoyService.addMemberEnjoyActivities(memberEnjoyActivities);//将从文件读取到的数据封装到对象 持久化到数据库
					impDataInfor.setTotalNum(childSheet.getLastRowNum());
					impDataInfor.setSucceedNum(childSheet.getLastRowNum() - errorNumbers.size());
					impDataInfor.setFailNum(errorNumbers.size());
					String errorDetail = "";
					if(errorNumbers.size()!=0){
						for(Integer num : errorNumbers){
							errorDetail = errorDetail+num+" ";
						}
					}
					impDataInfor.setFailDetail(errorDetail);
					impDataInfor.setFailResaon("1");
			} catch (Exception e) {   
				e.printStackTrace();   
			} 
		}
		this.setImpDataInfor(impDataInfor.toString());
        recache();
		return SUCCESS;
	}
	
	public String expMemberEnjoys(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String startDate = httpServletRequest.getParameter("startDate");
		String endDate = httpServletRequest.getParameter("endDate");
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		MemberEnjoyVO memberEnjoyVO = new MemberEnjoyVO();
		memberEnjoyVO.setStartDate(startDate);
		memberEnjoyVO.setEndDate(endDate);
		memberEnjoyVO.setRoleName(roleName);
		memberEnjoyVO.setUser(user);
		if(memberEnjoy==null){
			memberEnjoy = new MemberEnjoyActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 memberEnjoy.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 memberEnjoy.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 memberEnjoy.setSubCity(organ.getUm_organ_id());
			 }
		} 
		memberEnjoyVO.setMemberEnjoy(memberEnjoy);
		PagerModel pm = memberEnjoyService.findMemberEnjoyActivities(memberEnjoyVO, curPage);
		String realPath = httpServletRequest.getRealPath("/download/");
		String fileName = "会员专享活动信息.xls";
		String[] headers = {"活动日期","专享项目","分公司","中支机构","组织经费","参与人数","活动地点","OA审批号"}; 
		ExpMemberEnjoys.exp(headers,memberEnjoyService.findMemberEnjoyActivities(memberEnjoyVO,1,pm.getTotal()==0?1:pm.getTotal()).getDatas(),realPath+"/"+fileName);//将数据读取到服务器上的文件中
	    DownloadExcel.download(realPath,fileName,httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}

	public String expDemo(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		DownloadDemo.download(realPath,"MemberEnjoyDemo.xls;会员专享活动模板.xls",httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}

}
